package com.zw.yzk.kabu.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.model.CosplayModel;
import com.zw.yzk.kabu.utils.PhoneUtils;
import com.zw.yzk.kabu.utils.QNImageUtils;
import com.zw.yzk.kabu.utils.StringUtils;
import com.zw.yzk.kabu.view.activity.CosplayDetailsActivity;
import com.zw.yzk.kabu.view.activity.HomePageActivity;
import com.zw.yzk.kabu.view.activity.TopicListActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by zhanwei on 2017/1/11.
 */

public class HomePageCosAdapter extends RecyclerView.Adapter<HomePageCosAdapter.Holder> {

    private boolean self;
    private List<CosplayModel> dataList;
    private Context context;

    public HomePageCosAdapter(List<CosplayModel> list, boolean self) {
        dataList = new ArrayList<>();
        if (list != null) {
            dataList.addAll(list);
        }
        this.self = self;
    }

    public void refresh(List<CosplayModel> list) {
        dataList.clear();
        if (list != null) {
            dataList.addAll(list);
        }
        notifyDataSetChanged();
    }

    public void add(List<CosplayModel> list) {
        if (list != null) {
            int start = dataList.size();
            dataList.addAll(list);
            notifyItemRangeInserted(start, list.size());
        }
    }

    public List<CosplayModel> getTotalList() {
        return dataList;
    }

    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (context == null) {
            context = parent.getContext();
        }
        View rootView = LayoutInflater.from(context).inflate(R.layout.recycler_item_own_publish_list, parent, false);
        return new Holder(rootView);
    }

    @Override
    public void onBindViewHolder(final Holder holder, int position) {
        final CosplayModel model = dataList.get(position);

        holder.date.setText(model.getPublishTime());
        if (TextUtils.isEmpty(model.getPublishAddress())) {
            holder.location.setText(context.getResources().getString(R.string.unknown_address));
        } else {
            holder.location.setText(model.getPublishAddress());
        }
        holder.competition.setVisibility(model.isCompetition() ? View.VISIBLE : View.GONE);
        //设置文本样式
        SpannableString string = colorTextAndClickableWithPattern(
                model.getMessage(), StringUtils.DIVIDE_STRING_PATTERN1,
                ContextCompat.getColor(context, R.color.gold), context);
        SpannableString text = colorTextAndClickableWithPattern(
                string, StringUtils.DIVIDE_STRING_PATTERN2,
                ContextCompat.getColor(context, R.color.gold), context);
        holder.message.setText(text);
        holder.message.setMovementMethod(LinkMovementMethod.getInstance());
        holder.message.setHighlightColor(ContextCompat.getColor(context, R.color.transparent));
        if (TextUtils.isEmpty(model.getMessage())) {
            holder.message.setVisibility(View.GONE);
        }
        holder.praiseCount.setSelected(model.isPraise());
        holder.praiseCount.setText(String.valueOf(model.getPraiseCount()));
        holder.collect.setSelected(model.isCollected());
        holder.commentCount.setText(String.valueOf(model.getCommentCount()));
        if (self) {
            holder.collect.setVisibility(View.GONE);
            holder.delete.setVisibility(View.VISIBLE);
        } else {
            holder.delete.setVisibility(View.GONE);
            holder.collect.setVisibility(View.VISIBLE);
        }

        Glide.with(context)
                .load(QNImageUtils.getThumbnail(model.getCosUrl(), PhoneUtils.getScreenWidth(context), PhoneUtils.getScreenWidth(context)))
                .centerCrop()
                .error(R.drawable.im_default)
                .override(PhoneUtils.getScreenWidth(context), PhoneUtils.getScreenWidth(context))
                .into(holder.content);

        holder.content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, CosplayDetailsActivity.class);
                intent.putExtra(ActivityConstant.OPEN_COS_DETAIL_NAME, model.getPublisher());
                intent.putExtra(ActivityConstant.OPEN_COS_DETAIL_ID, model.getId());
                context.startActivity(intent);
            }
        });

        holder.praiseCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                dataList.get(holder.getAdapterPosition()).setPraise(!holder.praiseCount.isSelected());
//                notifyItemChanged(holder.getAdapterPosition());
                holder.praiseCount.setSelected(!holder.praiseCount.isSelected());
                if(listener != null) {
                    listener.praiseCos(model, holder.praiseCount.isSelected());
                }

            }
        });

        holder.commentCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, CosplayDetailsActivity.class);
                intent.putExtra(ActivityConstant.OPEN_COS_DETAIL_NAME, model.getPublisher());
                intent.putExtra(ActivityConstant.OPEN_COS_DETAIL_ID, model.getId());
                context.startActivity(intent);
            }
        });

        holder.collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                dataList.get(holder.getAdapterPosition()).setCollected(!holder.collect.isSelected());
                holder.collect.setSelected(!holder.collect.isSelected());
//                notifyItemChanged(holder.getAdapterPosition());
                if(listener != null) {
                    listener.collectCos(model, holder.collect.isSelected());
                }

            }
        });

        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener != null) {
                    listener.deleteCos(model);
                }
                dataList.remove(model);
                notifyItemRemoved(holder.getAdapterPosition());
            }
        });
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    /**
     * 给特定格式文本着色并添加点击事件
     *
     * @param source  源文本
     * @param pattern 格式
     * @param color   颜色
     * @return SpannableString
     */
    private SpannableString colorTextAndClickableWithPattern(String source, String pattern, int color, Context context) {
        if(TextUtils.isEmpty(source)) {
            return new SpannableString("");
        }
        SpannableString spanText = new SpannableString(source);
        List<String> patternResult = StringUtils.divideString(source, pattern);
        String remainString = source;
        int realStart = 0;
        for (String str : patternResult) {
            realStart += remainString.indexOf(str);
            spanText.setSpan(new ClickSpan(context), realStart, realStart + str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanText.setSpan(new ForegroundColorSpan(color), realStart, realStart + str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            remainString = remainString.substring(remainString.indexOf(str) + str.length());
            realStart += str.length();
        }

        return spanText;
    }

    /**
     * 给特定格式文本着色并添加点击事件
     *
     * @param source  源文本
     * @param pattern 格式
     * @param color   颜色
     * @return SpannableString
     */
    private SpannableString colorTextAndClickableWithPattern(SpannableString source, String pattern, int color, Context context) {
        if(source == null) {
            return new SpannableString("");
        }
        SpannableString spanText = source;
        List<String> patternResult = StringUtils.divideString(source.toString(), pattern);
        String remainString = source.toString();
        int realStart = 0;
        for (String str : patternResult) {
            realStart += remainString.indexOf(str);
            spanText.setSpan(new ClickSpan(context), realStart, realStart + str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanText.setSpan(new ForegroundColorSpan(color), realStart, realStart + str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            remainString = remainString.substring(remainString.indexOf(str) + str.length());
            realStart += str.length();
        }

        return spanText;
    }

    private static class ClickSpan extends ClickableSpan {

        private Context context;

        public ClickSpan(Context context) {
            this.context = context;
        }

        @Override
        public void onClick(View widget) {
            try {
                TextView tv = (TextView) widget;
                String s = tv.getText().subSequence(tv.getSelectionStart(),
                        tv.getSelectionEnd()).toString().replace("#", "");
                if(s.startsWith("@")) {
                    HomePageActivity.startHomePageActivity(context, 0, s.substring(1));
                } else {
                    TopicListActivity.startTopicActivity(context, s);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(ds.linkColor);
            ds.setUnderlineText(false);    //去除超链接的下划线
        }
    }

    public static class Holder extends RecyclerView.ViewHolder {

        @Bind(R.id.date)
        TextView date;
        @Bind(R.id.location)
        TextView location;
        @Bind(R.id.message)
        TextView message;
        @Bind(R.id.content)
        ImageView content;
        @Bind(R.id.praise)
        TextView praiseCount;
        @Bind(R.id.comment)
        TextView commentCount;
        @Bind(R.id.collect)
        TextView collect;
        @Bind(R.id.delete)
        TextView delete;
        @Bind(R.id.competition)
        ImageView competition;

        public Holder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public interface CosActionListener {
        void praiseCos(CosplayModel model, boolean praise);

        void collectCos(CosplayModel model, boolean collect);

        void deleteCos(CosplayModel model);
    }

    private CosActionListener listener;

    public void setCosActionListener(CosActionListener listener) {
        this.listener = listener;
    }
}
